package com.example.springboot.config.redis.compress;

import com.example.springboot.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @author chenzhangkun
 * @ClassName CompressRedis
 * @description: TODO
 * @date 2024年11月01日
 */
public class CompressRedis extends JdkSerializationRedisSerializer {
	public static final int BUFFER_SIZE = 4096;

	private Jackson2JsonRedisSerializer<User> jackson2JsonRedisSerializer;

	public CompressRedis() {
		super();
		jackson2JsonRedisSerializer = getValueSerializer();
	}
	private static Jackson2JsonRedisSerializer<User> getValueSerializer() {
		Jackson2JsonRedisSerializer<User> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(User.class);
		ObjectMapper mapper=new ObjectMapper();
		jackson2JsonRedisSerializer.setObjectMapper(mapper);
		return jackson2JsonRedisSerializer;
	}

	@Override
	public byte[] serialize(Object graph) {
		if (graph==null){
			return new byte[0];
		}
		ByteArrayOutputStream bos=null;
		GZIPOutputStream gizp=null;
		try {
			byte[] bytes = jackson2JsonRedisSerializer.serialize(graph);
			System.out.println("压缩前lenth="+bytes.length);
			bos=new ByteArrayOutputStream();
			gizp=new GZIPOutputStream(bos);
			// 压缩
			gizp.write(bytes);
			gizp.finish();
			byte[] result = bos.toByteArray();
			System.out.println("压缩后length="+result.length);
			return new BASE64Encoder().encode(result).getBytes();
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			IOUtils.closeQuietly(bos);
			IOUtils.closeQuietly(gizp);
		}
		return null;
	}

	@Override
	public Object deserialize(byte[] bytes) {
		if (bytes == null || bytes.length == 0) {
			return null;
		}
		ByteArrayOutputStream bos = null;
		ByteArrayInputStream bis = null;
		GZIPInputStream gzip = null;
		try {
			bos = new ByteArrayOutputStream();
			byte[] compressed = new sun.misc.BASE64Decoder().decodeBuffer( new String(bytes));;
			bis = new ByteArrayInputStream(compressed);
			gzip = new GZIPInputStream(bis);
			byte[] buff = new byte[BUFFER_SIZE];
			int n;


			// uncompress
			while ((n = gzip.read(buff, 0, BUFFER_SIZE)) > 0) {
				bos.write(buff, 0, n);
			}
			//deserialize
			Object result = jackson2JsonRedisSerializer.deserialize(bos.toByteArray());
			return result;
		} catch (Exception e) {
			throw new SerializationException("Gzip deserizelie error", e);
		} finally {
			IOUtils.closeQuietly(bos);
			IOUtils.closeQuietly(bis);
			IOUtils.closeQuietly(gzip);
		}
	}
}
